//
//  LocationListViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/19.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "LocationListViewController.h"
#import "LocationAddress.h"

#import "City.h"
#import "Province.h"
#import "District.h"


static NSString *addressCellID = @"addressCellID";

#define titileScrollViewHeight jisuan(90)
#define leftMargin jisuan(50)
#define margin jisuan(60)

@interface LocationListViewController ()<UITableViewDelegate, UITableViewDataSource>

// 阴影界面
@property (strong, nonatomic) UIView *coverView;

@property (strong, nonatomic) UIView *addressView;
@property (strong, nonatomic) UIScrollView *titleScrollView;
@property (strong, nonatomic) UIView *sliderView;
@property (strong, nonatomic) UITableView *addressTableView;

@property (assign, nonatomic) CGFloat totolLableX;
@property (strong, nonatomic) NSArray *locData;


@property (strong, nonatomic) NSArray *provinceArr;
@property (strong, nonatomic) NSArray *cityArr;
@property (strong, nonatomic) NSArray *districtArr;

@property (assign, nonatomic) NSInteger tableViewType;

@property (copy, nonatomic) NSString *provinceStr;
@property (copy, nonatomic) NSString *cityStr;
@property (copy, nonatomic) NSString *districtStr;

@property (strong, nonatomic) NSMutableArray *canSelectedCityArr;
@property (strong, nonatomic) NSMutableArray *canSelectedistrictArr;

@property (copy, nonatomic) NSString *num;

@property (assign, nonatomic) BOOL isFirst;

@property (strong, nonatomic) NSMutableArray *labelArr;

@property (strong, nonatomic) NSArray *titileArr;

@end

@implementation LocationListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}


+ (instancetype)locationListInstance {
    
    static LocationListViewController *listVC;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        listVC = [[self alloc] init];
        
        listVC.isFirst = YES;
        listVC.labelArr = [NSMutableArray array];
   
    });
    
    return listVC;
    
}

#pragma mark -lable点击事件
- (void)labelGestureClick:(UIGestureRecognizer *)recognizer {
    
    UILabel *lable = (UILabel *)recognizer.view;
    
    self.tableViewType = lable.tag;
    
    if (self.tableViewType == 0) {
        
        [self sliderAnimationWithLabel:lable];
    }
    
    if (self.tableViewType == 1) {
        
        if (self.provinceStr) {
            
            [self sliderAnimationWithLabel:lable];
            
        }else {
            
            NSLog(@"请选择省份");
            
        }
        
    }
    
    if (self.tableViewType == 2) {
        
        if (self.cityStr) {
            
            [self sliderAnimationWithLabel:lable];
            
        }else {
            
            NSLog(@"请选择城市");
            
        }
        
    }

}

- (void)sliderAnimationWithLabel:(UILabel *)lable {
    
//    self.tableViewType = lable.tag;
    
    [self.addressTableView reloadData];
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        
        CGRect rect = weakSelf.sliderView.frame;
        rect.origin.x = lable.x;
        rect.size.width = lable.width;
        weakSelf.sliderView.frame = rect;
        
    }];
    
}

#pragma mark -点击黑色背景移除视图
- (void)coverGestureClick:(UIGestureRecognizer *)recognizer {
    
    [self close];
    
}

- (void)close {
    
    [self.view removeFromSuperview];
    [self.coverView removeFromSuperview];
    [self.addressView removeFromSuperview];
    [self.addressTableView removeFromSuperview];
    [self.titleScrollView removeFromSuperview];
    
}

- (void)setupUI {
    
//    if (self.isFirst) {
    
    [self createUI];
        
//        self.isFirst = NO;
//    }
    
}

- (void)createUI {
    
    self.tableViewType = 0;
    self.provinceStr = nil;
    self.cityStr = nil;
    self.districtStr = nil;
    self.num = 0;
    [self.canSelectedCityArr removeAllObjects];
    [self.canSelectedistrictArr removeAllObjects];
    

    NSLog(@"%@", self.locData);
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.view];
    [self.view bringSubviewToFront:[UIApplication sharedApplication].keyWindow];
    
    [self.view addSubview:self.coverView];
    [self.view addSubview:self.addressView];
    [self.addressView addSubview:self.titleScrollView];
    [self.addressView addSubview:self.addressTableView];

    __weak typeof(self) weakSelf = self;
    [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
        make.top.mas_equalTo(weakSelf.view.mas_top);
        
    }];

    [self.addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(jisuan(800));
    }];
    [self.titleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.addressView.mas_left);
        make.right.mas_equalTo(weakSelf.addressView.mas_right);
        make.top.mas_equalTo(weakSelf.addressView.mas_top);
        make.height.mas_equalTo(titileScrollViewHeight);
    }];
    [self.addressTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.addressView.mas_left);
        make.right.mas_equalTo(weakSelf.addressView.mas_right);
        make.bottom.mas_equalTo(weakSelf.addressView.mas_bottom);
        make.top.mas_equalTo(weakSelf.titleScrollView.mas_bottom);
        
    }];

    [self.labelArr removeAllObjects];
    
    
    if (self.isFirst) {
        
        [self scrollViewTitleScrollview];
        
        self.isFirst = NO;
        
    }else {
        
        [self changeTitleScrollviewTitle];
    }
    
    
    [self.addressTableView reloadData];


}
- (void)changeTitleScrollviewTitle {
    
    self.totolLableX = 0.0;
    
    for (int i = 0; i < 3; i ++) {
        
        UILabel *label = self.titleScrollView.subviews[i];
        
        [self createTitleWithLabel:label andTag:i];

    }
    
    UILabel *temp = [self.titleScrollView.subviews firstObject];
    NSLog(@"%.2f===%.2f\n %@", temp.x , temp.width, self.titleScrollView.subviews);
    self.sliderView.frame = CGRectMake(temp.x, jisuan(80), temp.width, jisuan(4));
    [self.titleScrollView addSubview:self.sliderView];
    
    
    UILabel *lastTemp = [self.titleScrollView.subviews lastObject];
    self.titleScrollView.contentSize = CGSizeMake(self.totolLableX + lastTemp.width + leftMargin, 0);
}

- (void)createTitleWithLabel:(UILabel *)label andTag:(NSInteger)tag {
    
    label.userInteractionEnabled = YES;
    label.tag = tag;
    label.text = self.titileArr[tag];
    
    label.textColor = Color333333;
    label.font = Font(28);
    label.textAlignment = NSTextAlignmentLeft;
    [label sizeToFit];
    
    CGFloat x = (label.width + margin) * tag + leftMargin;
    
    self.totolLableX = x;
    
    label.frame = CGRectMake(x, 0, label.width, titileScrollViewHeight);
    
    
}


- (void)scrollViewTitleScrollview {
    
    self.totolLableX = 0.0;
    
    for (int i = 0; i < 3; i ++) {
        
        UILabel *label = [[UILabel alloc] init];
        
        [self createTitleWithLabel:label andTag:i] ;

        [self.titleScrollView addSubview:label];
        
        UITapGestureRecognizer *labelGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelGestureClick:)];
        [label addGestureRecognizer:labelGesture];

    }
    
    UILabel *temp = [self.titleScrollView.subviews firstObject];
    
    NSLog(@"%.2f===%.2f\n %@", temp.x , temp.width, self.titleScrollView.subviews);
    self.sliderView.frame = CGRectMake(temp.x, jisuan(80), temp.width, jisuan(4));
    [self.titleScrollView addSubview:self.sliderView];
    
    
    UILabel *lastTemp = [self.titleScrollView.subviews lastObject];
    self.titleScrollView.contentSize = CGSizeMake(self.totolLableX + lastTemp.width + leftMargin, 0);

}

#pragma mark -delegate \ datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.tableViewType == 0) {
        
        return self.provinceArr.count;

    }else if (self.tableViewType == 1) {
        
        return self.canSelectedCityArr.count;
        
    }else {
        
        return self.canSelectedistrictArr.count;
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:addressCellID];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addressCellID];
    }
    
    if (self.tableViewType == 0) {
        
        Province *provinceModel = self.provinceArr[indexPath.row];
        cell.textLabel.text = provinceModel.n;
    
    }else if (self.tableViewType == 1) {
        
        City *cityModel = self.canSelectedCityArr[indexPath.row];
        cell.textLabel.text = cityModel.n;
    
    }else {
        
        District *districtModel = self.canSelectedistrictArr[indexPath.row];
        cell.textLabel.text = districtModel.n;
        
    }
    
    cell.textLabel.textColor = Color333333;
    cell.textLabel.font = Font(24);
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
 
    return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.tableViewType == 0) {
        
        Province *provinceModel = self.provinceArr[indexPath.row];
        
        self.provinceStr = provinceModel.n;
        self.num = provinceModel.i;
        [self selecteCity];
        
        [self changeTitleScrollViewWith:self.provinceStr];
        
        self.tableViewType = 1;
        [self sliderAnimation];

    }else if (self.tableViewType == 1) {
        
        City *cityModel = self.canSelectedCityArr[indexPath.row];
        
        self.cityStr = cityModel.n;
        self.num = cityModel.i;
        [self selectedDistrics];
        
        [self changeTitleScrollViewWith:self.cityStr];
        
        self.tableViewType = 2;
        [self sliderAnimation];
        
        if (self.tableViewType == 2) {
            
            if (self.canSelectedistrictArr.count <= 0) {
                
                if (self.addressBlock) {
                    
                    self.addressBlock(self.provinceStr, self.cityStr, @"");
                }
                
                [self close];
            }

        }
    
    }else {
        
        District *districtModel = self.canSelectedistrictArr[indexPath.row];
        self.districtStr = districtModel.n;
        
        [self changeTitleScrollViewWith:self.districtStr];
        
        if (self.addressBlock) {
            
            self.addressBlock(self.provinceStr, self.cityStr, self.districtStr);
        }
        
        [self close];
        
    }
    
}

- (void)changeTitleScrollViewWith:(NSString *)titleStr {
    
    CGFloat width = 0.0;
    

    self.totolLableX = leftMargin;
    
    for (int i = 0; i < 3; i ++) {
        
        UILabel *label = self.titleScrollView.subviews[i];
        width = label.width;
        NSLog(@"%.2f",label.width);
        
        label.font = Font(28);
       
        if (self.tableViewType == label.tag) {
            
            label.text = titleStr;
            [label sizeToFit];
            NSLog(@"%.2f",label.width);
            
        }
        
        [self.labelArr addObject:label];
        
        if (i != 0) {
            
            UILabel *tempL = self.labelArr[i - 1];
            self.totolLableX = self.totolLableX + tempL.width + margin;
            
        }
        
        label.frame = CGRectMake(self.totolLableX, 0, label.width, titileScrollViewHeight);
        
    }
    
    UILabel *label = self.titleScrollView.subviews[self.tableViewType];

    self.titleScrollView.contentSize = CGSizeMake(self.totolLableX + label.width + leftMargin, 0);
    
    NSLog(@"%@",self.titleScrollView.subviews);
    
}

- (void)sliderAnimation {
    
    UILabel *label = self.titleScrollView.subviews[self.tableViewType];
    
    NSLog(@"%.2f\n%.2f",label.width, label.x);
    
    CGFloat width = self.titleScrollView.frame.size.width;
    CGFloat offsetX = label.center.x - width * 0.5;
    
    // 最大偏移量
    CGFloat maxOffsetx = self.titleScrollView.contentSize.width - width;
    if (offsetX < 0) {
        offsetX = 0;
    } else if (offsetX > maxOffsetx) {
        offsetX = maxOffsetx;
    }
    
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3
                     animations:^{
                         
                         CGRect rect = weakSelf.sliderView.frame;
                         rect.origin.x = label.x;
                         rect.size.width = label.width;
                         weakSelf.sliderView.frame = rect;
                         
                     }];
    
    [self.addressTableView reloadData];
    
}


- (void)selecteCity {
    
    [self.canSelectedCityArr removeAllObjects];

    
    for (int i = 0 ; i < self.cityArr.count; i++) {
        
        City *cityModel = self.cityArr[i];
        
        if ([cityModel.p isEqualToString:self.num]) {
            
            [self.canSelectedCityArr addObject:cityModel];
       
        }
        
    }
    
}

- (void)selectedDistrics {
    
    [self.canSelectedistrictArr removeAllObjects];
    
    for (int i = 0 ; i < self.cityArr.count; i++) {
        
         District *districtModel = self.districtArr[i];
        
        if ([districtModel.p isEqualToString:self.num]) {
            
            [self.canSelectedistrictArr addObject:districtModel];
            
        }
        
    }
    
}

#pragma mark -lazy
- (UIView *)coverView {
    
    if (!_coverView) {
        
        _coverView = [[UIView alloc] init];
        _coverView.backgroundColor = Color000000;
        _coverView.alpha = 0.4;
        
        UITapGestureRecognizer *coverGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverGestureClick:)];
        [_coverView addGestureRecognizer:coverGesture];
        
    }
    
    return _coverView;
}

- (UIView *)addressView {
    
    if (!_addressView) {
        
        _addressView = [[UIView alloc] init];
        _addressView.backgroundColor = WhiteColor;

    }
    
    return _addressView;
}

- (UIScrollView *)titleScrollView {
    
    if (!_titleScrollView) {
        
        _titleScrollView = [[UIScrollView alloc] init];
        _titleScrollView.backgroundColor = WhiteColor;
        
        _titleScrollView.showsVerticalScrollIndicator = NO;
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        
    }
    
    return _titleScrollView;
}

- (UIView *)sliderView {
    
    if (!_sliderView) {
        
        _sliderView = [[UIView alloc] init];
        _sliderView.backgroundColor = Colorff0000;
        
    }
    
    return _sliderView;
}

- (UITableView *)addressTableView {
    
    if (!_addressTableView) {
     
        _addressTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        
        _addressTableView.separatorStyle = UITableViewCellSelectionStyleNone;
        
        _addressTableView.delegate = self;
        _addressTableView.dataSource = self;
        
        _addressTableView.showsVerticalScrollIndicator = NO;
        _addressTableView.showsHorizontalScrollIndicator = NO;
        
        _addressTableView.estimatedRowHeight = 0;
        _addressTableView.estimatedSectionFooterHeight = 0;
        _addressTableView.estimatedSectionHeaderHeight = 0;
        
        if (@available(iOS 11.0, *)) {
        
            _addressTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        }
        
    }
    
    return _addressTableView;
}

- (NSArray *)locData {
    
    if (!_locData) {
        
        NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"address" ofType:@"json"]];
        
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

        LocationAddress *model = [LocationAddress mj_objectWithKeyValues:dataDict];
        
        NSMutableArray *provinceArr = model.province;
        NSMutableArray *cityArr = model.city;
        NSMutableArray *districtArr = model.district;
        
        self.provinceArr = [provinceArr copy];
        self.cityArr = [cityArr copy];
        self.districtArr = [districtArr copy];
    
    }
    
    return _locData;
    
}

- (NSMutableArray *)canSelectedCityArr {
    
    if (!_canSelectedCityArr) {
        
        _canSelectedCityArr = [NSMutableArray array];
    
    }
    
    return _canSelectedCityArr;
}
- (NSMutableArray *)canSelectedistrictArr {
    
    if (!_canSelectedistrictArr) {
        
        _canSelectedistrictArr = [NSMutableArray array];
   
    }
    
    return _canSelectedistrictArr;
}

- (NSArray *)titileArr {

    if (!_titileArr) {
        
        _titileArr = @[@"省份", @"城市", @"区县"];
    }
    
    return _titileArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
